#!/usr/local/python3.7/bin python3

__author__ = '无崖子'

from django.utils.deprecation import MiddlewareMixin
from app_distribution_platform.models import Logs
from django.http import HttpResponsePermanentRedirect
import re


class RedirectMiddle(MiddlewareMixin):
    @staticmethod
    def process_request(request):
        HOST = 'https://www.88pxh.com'
        host = request.get_host()
        if request.method != 'HEAD' and request.META['HTTP_X_FORWARDED_PROTO'] == 'http':
            return HttpResponsePermanentRedirect(HOST + request.get_full_path())
        if request.method != 'HEAD' and host == '88pxh.com':
            return HttpResponsePermanentRedirect(HOST + request.get_full_path())
        url = request.get_full_path()
        if re.findall('^/app/list', url):
            if 'page' in url:
                return HttpResponsePermanentRedirect(
                    HOST + '/app/page_' + re.search('\d+', url, flags=0).group())
            else:
                return HttpResponsePermanentRedirect(HOST + '/app')
        elif re.findall('^/app/category', url):
            category_id = int(re.search('\d+', url, flags=0).group())
            shorthand_list = ['xkz', 'dqd', 'xed', 'gtg', 'fkk', 'dlx']
            if 'page' in url:
                page = url.split('/')[url.split('/').index('page') + 1]
                return HttpResponsePermanentRedirect(HOST + '/app/' + shorthand_list[category_id - 1] + '/page_' + page)
            else:
                return HttpResponsePermanentRedirect(HOST + '/app/' + shorthand_list[category_id - 1])
        elif re.findall('^/app/detail/article', url):
            return HttpResponsePermanentRedirect(
                HOST + '/app/article/' + re.search('\d+', url, flags=0).group() + '.html')
        elif re.findall('^/app/detail', url):
            return HttpResponsePermanentRedirect(
                HOST + '/app/' + re.search('\d+', url, flags=0).group() + '.html')


class AddressMiddle(MiddlewareMixin):

    @staticmethod
    def process_response(request, response):
        path = request.get_full_path()
        if request.method != 'HEAD' and 'static' not in path and 'manage' not in path:
            ip = request.META['HTTP_REMOTEIP']
            user_agent = request.META.get('HTTP_USER_AGENT')
            status_code = response.status_code
            try:
                referer = request.META['HTTP_REFERER']
                log = Logs(path=path, ip=ip, user_agent=user_agent, referer=referer, status_code=status_code)
            except:
                log = Logs(path=path, ip=ip, user_agent=user_agent, status_code=status_code)
            log.save()
        return response
